<template>
	<view class="my">
		<!--头部-->
		<view class="my-head">
			<image class="my-head-pic" :src="avatar" alt="用户头像" @tap="chooseImage" />
			<view class="my-head-text">
				<input type="text" class="nickname-input" v-model="nickname" @blur="saveNickname" />
			</view>
		</view>
		<view class="my-gap">
		</view>
		<view>
			<view v-if="!userPhoneNumber">
				<navigator url="/pages/login/login" hover-class="navigator-hover">
					<view class="content-item">登录</view>
				</navigator>
			</view>
			<navigator url="/pages/feedback/feedback" hover-class="navigator-hover">
				<view class="content-item">意见反馈</view>
			</navigator>
			<view v-if="userPhoneNumber">
				<navigator url="/pages/logout/logout" hover-class="navigator-hover">
					<view class="content-item">退出登录</view>
				</navigator>
			</view>
			<navigator url="/pages/help/help" hover-class="navigator-hover">
				<view class = "content-item">使用帮助</view>
			</navigator>
			<view class="Customer-Service">
				<uni-section title="联系我们" type="line" padding>
					<text>
						公司：乐松源科技（苏州）有限公司
						客服电话: 0512-53557636 
						电话时间: 9:00-17:00
					</text>				
				</uni-section>
			</view>	
			
			<view v-if="showProgressBar" class="progress-bar">
				<view class="progress-bar-inner" :style="{ width: progress + '%' }"></view>
			</view>
			<!-- 版本号显示和检查更新按钮 -->
			<view class="app-version">
				<text>App 版本号: {{ currentVersion }}</text>
				<button plain="true" style="margin-top: 30rpx;" :disabled="showProgressBar"
					@click="checkForUpdates">检查更新</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				avatar: '',
				nickname: '用户昵称',
				userPhoneNumber: uni.getStorageSync('userPhoneNumber'),
				appVersion: '', // 后端返回版本号
				currentVersion: '', // 当前版本号
				showProgressBar: false,
				progress: 0
			}
		},
		onShow() {
			this.userPhoneNumber = uni.getStorageSync('userPhoneNumber');
			// this.avatar = uni.getStorageSync('avatar') || '../../static/avatar.png';
			// console.log(this.avatar);
			this.getUserInfo();
		},
		created() {
			plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
				console.log(wgtinfo.version); //应用版本号
				this.currentVersion = wgtinfo.version;
			})
			this.getAppVersion();


		},
		methods: {
			chooseImage() {
				if (!this.userPhoneNumber) {
					uni.showToast({
						title: '请登录',
						icon: 'none',
						duration: 2000
					});
				} else {
					uni.chooseImage({
						count: 1,
						sizeType: ['original', 'compressed'],
						sourceType: ['album', 'camera'],
						success: (res) => {
							const tempFilePaths = res.tempFilePaths;
							this.avatar = tempFilePaths[0];
							// uni.setStorageSync('avatar', this.avatar);
							const filePath = tempFilePaths[0];
							const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
							const fileExtension = fileName.substring(fileName.lastIndexOf('.'));
							const newFileName = 'avatar' + fileExtension;

							uni.uploadFile({
								url: this.$baseUrl + '/user/account/uploadprofile',
								filePath: tempFilePaths[0],
								name: 'mFile',
								header: {
									'content-type': 'application/x-www-form-urlencoded',
									'token': uni.getStorageSync('token')
								},
								formData: {
									'phone': this.userPhoneNumber,
									'newName': newFileName
								},
								success: (uploadFileRes) => {
									console.log('上传成功', uploadFileRes);
									this.getUserInfo();
								},
								fail: (uploadFileError) => {
									console.error('上传失败', uploadFileError);
								}
							});
						}
					});
				}
			},
			getUserInfo() {
				uni.request({
					url: this.$baseUrl + '/user/account/getbyphone/' + uni.getStorageSync('userPhoneNumber'),
					method: 'GET',
					header: {
						'token': uni.getStorageSync('token')
					},
					success: (res) => {
						console.log(res);
						if (res.statusCode === 200) {
							this.nickname = res.data.data.username;
							uni.setStorageSync('userName',this.nickname);
							if (res.data.data.profileUrl) {
								this.avatar = res.data.data.profileUrl;
							} else {
								this.avatar = '../../static/avatar.png'
							}
						} else {
							console.log('获取用户信息失败', res);
						}
					},
					fail: (err) => {
						console.log('请求用户信息失败', err);
					}
				});
			},
			saveNickname() {
				if (!this.userPhoneNumber) {
					uni.showToast({
						title: '请登录',
						icon: 'none',
						duration: 2000
					});
				} else {
					uni.request({
						url: this.$baseUrl + '/user/account/update',
						method: 'POST',
						data: {
							username: this.nickname,
							phone: this.userPhoneNumber
						},
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'token': uni.getStorageSync('token')
						},
						success: (res) => {
							if (res.data.code === 0) {
								uni.setStorageSync('userName',this.nickname);
								console.log('用户昵称修改成功', res);
								console.log('用户昵称', uni.getStorageSync('userName'));
							} else {
								console.error('用户昵称修改失败：', res);
							}
						},
						fail: (err) => {
							console.error('用户昵称请求错误：', err);
							uni.showToast({
								title: '请求错误',
								icon: 'none',
								duration: 2000
							});
						}
					});
				}
			},
			getAppVersion() {
				uni.request({
					url: this.$baseUrl + '/download/app/version',
					method: 'GET',
					data: {
						extName: 'apk'
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'token': uni.getStorageSync('token')
					},
					success: (res) => {
						console.log('获取版本号的返回', res);
						if (res.data.code === 0) {
							this.appVersion = res.data.data;
							this.checkForUpdates();
						} else {
							console.error('获取App版本号失败：', res.data.message);
						}
					},
					fail: (err) => {
						console.error('请求App版本号失败：', err);
					}
				});
			},
			checkForUpdates() {
				if (this.appVersion > this.currentVersion) {
					uni.showModal({
						title: '新版本可用',
						content: '请更新到最新版本。',
						showCancel: false, // 禁止取消按钮
						success: (res) => {
							if (res.confirm) {
								this.downloadAppUpdate();
							}
						}
					});
				} else {
					uni.showToast({
						title: '已是最新版本',
						icon: 'none'
					});
				}
			},
			downloadAppUpdate() {
				const version = this.appVersion;
				const downloadUrl = this.$baseUrl + `/download/app/apk/appV${version}.apk`; // 动态生成下载链接
				this.showProgressBar = true;
				this.progress = 0;
				const downloadTask = uni.downloadFile({
					url: downloadUrl,
					success: (downloadResult) => {
						if (downloadResult.statusCode === 200) {
							// 下载成功，提示用户安装
							uni.showModal({
								title: '下载完成',
								content: '新版本已下载完成，请安装。',
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										// 打开安装文件
										uni.openDocument({
											filePath: downloadResult.tempFilePath,
											fileType: 'apk',
											success: () => {
												console.log('打开安装文件成功');
												this.showProgressBar = false;
												this.progress = 0;
											},
											fail: (err) => {
												console.error('打开安装文件失败', err);
												this.showProgressBar = false;
												this.progress = 0;
											}
										});
									}
								}
							});
						} else {
							uni.showToast({
								title: '下载失败，请稍后再试',
								icon: 'none'
							});
							this.showProgressBar = false;
							this.progress = 0;
						}
					},
					fail: (err) => {
						console.error('下载失败', err);
						uni.showToast({
							title: '下载失败，请检查网络连接',
							icon: 'none'
						});
						this.showProgressBar = false;
						this.progress = 0;
					}
				});

				downloadTask.onProgressUpdate((res) => {
					this.progress = res.progress;
				});
			},
		}
	}
</script>

<style>
	.progress-bar {
		width: 80%;
		height: 20px;
		background-color: #f3f3f3;
		border-radius: 10rpx;
		overflow: hidden;
		margin: 20rpx auto;
		position: relative;
		margin-top: 100rpx;
	}

	.progress-bar-inner {
		height: 100%;
		background-color: #4caf50;
		width: 0%;
		transition: width 0.2s;
	}

	.content-item {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		margin: 20rpx auto;
		padding: 20rpx;
		border-bottom: 2px solid #ccc;
	}

	.my-gap {
		background-color: rgb(226, 226, 226);
		width: 100%;
		height: 30rpx;
	}

	.my-head {
		background-color: #ccc;
		width: 100%;
		height: 350rpx;
		position: relative;
	}

	.my-head-pic {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		margin-top: 80rpx;
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
	}

	.my-head-text {
		position: absolute;
		left: 50%;
		top: 240rpx;
		transform: translateX(-50%);
		width: 200rpx;
		display: flex;
		justify-content: center;
	}

	.nickname-input {
		width: 100%;
		text-align: center;
		font-size: 30rpx;
		border: none;
		background: none;
		outline: none;
	}

	.app-version {
		position: absolute;
		top: 600px;
		/* 距离父元素顶部 50px */
		left: 110px;
		/* 距离父元素左侧 40px */
		width: 150px;
		height: 100px;
		padding: 20rpx;
		text-align: center;
		font-size: 30rpx;
	}
</style>